package com.util.vmwareops;

import com.vmware.vim25.mo.*;
import com.vmware.vim25.ws.Client;
import java.net.URL;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.vmware.vim25.CustomFieldDef;
import com.vmware.vim25.CustomFieldValue;
import javafx.scene.chart.PieChart;
import sun.nio.ch.Net;
import com.vmware.vim25.*;

import java.sql.Connection;
import java.sql.Statement;
import java.util.concurrent.Executors;

@Deprecated
public class ClusterComputeResourceSummary {

    /*
    private String versionId;

    public String getVersionId() {
        return versionId;
    }

    public void setVersionId(String versionId) {
        this.versionId = versionId;
    }

    // 从VC中拉取集群信息
    private List<ClusterComputeResource> getCluster(ServiceInstance si) throws Exception {

        // 获取根目录
        Folder rootFolder = si.getRootFolder();

        // 获取集群资源
        ManagedEntity[] managedEntityList;
        managedEntityList = new InventoryNavigator(rootFolder).searchManagedEntities("ClusterComputeResource");
        // 遍历集群资源，获取物理主机和虚拟机
        // 获取集群列表
        List<ClusterComputeResource> clusterList = new ArrayList<ClusterComputeResource>();
        for (ManagedEntity entity : managedEntityList) {
            ClusterComputeResource cluster = (ClusterComputeResource) entity;
            clusterList.add(cluster);
        }
        return clusterList;
    }

    // 将集群信息更新至数据库
    private List<ClusterInfo> updateCluster(Connection con, VCenterInfo vc, List<ClusterComputeResource> clusterList) throws SQLException {
        System.out.println(String.format("[INFO] Update Cluster start"));

        List<ClusterInfo> clusterInfo = new ArrayList<ClusterInfo>();

        Statement stmt = null;
        stmt = con.createStatement();

        for(ClusterComputeResource cluster : clusterList) {
            ClusterInfo tmp = new ClusterInfo(
                    MyUtils.getUUID("CLUSTER"),
                    vc,
                    cluster.getMOR().getVal(),
                    cluster.getName(),
                    cluster.getSummary().getNumCpuCores(),
                    cluster.getSummary().getTotalMemory() / 1024.0 / 1024.0 / 1024.0,
                    this.versionId
            );
            clusterInfo.add(tmp);
            String sql_command = String.format(
                    "insert into resource_bundle_vsphere_cluster values(\"%s\", \"%s\", \"%s\", \"%s\", %d, %.2f, \"%s\")",
                    tmp.getId(),
                    tmp.getVc().getId(),
                    tmp.getDomainName(),
                    tmp.getName(),
                    tmp.getCpu(),
                    tmp.getMem(),
                    tmp.getVersionId()
            );
            // System.out.println(sql_command);
            stmt.execute(sql_command);
        }

        System.out.println(String.format("[INFO] Update Cluster end"));
        return clusterInfo;
    }
    private List<HostInfo> updateHost(Connection con, ClusterInfo clusterInfo, HostSystem[] hosts) throws SQLException {
        System.out.println(String.format("[INFO] Update host start"));

        List<HostInfo> hostInfo = new ArrayList<HostInfo>();

        Statement stmt = null;
        stmt = con.createStatement();

        for(HostSystem host : hosts) {
            HostInfo tmp = new HostInfo(
                    MyUtils.getUUID("HOST"),
                    host.getSummary().hardware.getUuid(),
                    host.getMOR().getVal(),
                    clusterInfo,
                    host.getName(),
                    host.getRuntime().getPowerState().toString(),
                    host.getRuntime().getConnectionState().toString(),
                    host.getSummary().hardware.numCpuCores,
                    host.getSummary().hardware.memorySize,
                    this.versionId
            );
            hostInfo.add(tmp);
            String sql_command = String.format(
                    "insert into resource_bundle_vsphere_host values(\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", %d, %.2f, \"%s\")",
                    tmp.getId(),
                    tmp.getUuid(),
                    tmp.getDomainName(),
                    tmp.getCluster().getId(),
                    tmp.getName(),
                    tmp.getPowerState(),
                    tmp.getConnectState(),
                    tmp.getCpu(),
                    tmp.getMem(),
                    tmp.getVersionId()
            );
            // System.out.println(sql_command);
            stmt.execute(sql_command);
        }

        System.out.println(String.format("[INFO] Update host end"));
        return hostInfo;
    }


    private List<VMInfo> updateVM(Connection con, HostInfo host, VirtualMachine[] vms) throws SQLException {
        System.out.println(String.format("[INFO] Update VM start"));

        List<VMInfo> vmInfo = new ArrayList<VMInfo>();
        Statement stmt = null;
        stmt = con.createStatement();

        for(VirtualMachine vm : vms) {
            // 获取端口组字符串
            String networkStr = "";
            try {
                Network[] net = vm.getNetworks();
                for (Network n : net) {
                    networkStr += n.getName() + "\n";
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }

            // 获取自定义属性
            String prop = "";
            if(vm.getCustomValue() != null) {
                for (CustomFieldValue cusfield : vm.getCustomValue()) {
                    CustomFieldStringValue name = (CustomFieldStringValue) cusfield;
                    prop += name.getValue() + "\n";
                }
            }

            VMInfo tmp = new VMInfo(
                    MyUtils.getUUID("VM"),
                    vm.getConfig().uuid,
                    host,
                    vm.getName(),
                    vm.getGuest().hostName,
                    vm.getGuest().ipAddress,
                    networkStr,
                    vm.getRuntime().powerState.toString(),
                    vm.getRuntime().connectionState.toString(),
                    vm.getConfig().hardware.numCPU,
                    vm.getConfig().hardware.memoryMB / 1024.0,
                    vm.getSummary().storage.uncommitted / 1024.0 / 1024.0 / 1024.0,
                    prop,
                    "",
                    this.versionId
            );

            vmInfo.add(tmp);
            String sql_command = String.format(
                    "insert into resource_bundle_vsphere_vm values(\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", %d, %.2f, %.2f,  \"%s\", \"%s\", \"%s\")",
                    tmp.getId(),
                    tmp.getUuid(),
                    tmp.getHost().getId(),
                    tmp.getName(),
                    tmp.getHostname(),
                    tmp.getIpAddress(),
                    tmp.getNetwork(),
                    tmp.getPowerState(),
                    tmp.getConnectState(),
                    tmp.getCpu(),
                    tmp.getMem(),
                    tmp.getStorage(),
                    tmp.getCIName(),
                    tmp.getCIAppname(),
                    tmp.getVersionId()
            );
            // System.out.println(sql_command);
            stmt.execute(sql_command);
        }

        System.out.println(String.format("[INFO] Update VM end"));
        return vmInfo;
    }

    public synchronized void update(VCenterInfo vc, VCConnectionPool vcPool, String versionId) throws Exception {

        System.out.println(String.format("[INFO] Update VC:%s start", vc.getHostname()));

        this.setVersionId(versionId);

        // 从VC连接池中获取VC连接
        ServiceInstance si = vcPool.getConnnection();

        System.out.println("Get VC Connection !");

        // 获取DB连接池连接
        DBConnectionPool dbPool = DBConnectionPoolFactory.getDBConnectionPool("vmwareops");
        Connection con = dbPool.getConnnection();
        System.out.println("Get DB Connection !");
        con.setAutoCommit(false);

        // 获取集群资源信息
        List<ClusterComputeResource> clusterList = this.getCluster(si);
        // 更新集群数据库，并返回集群的信息类列表，方便后续更新host（获取cluster id）
        List<ClusterInfo> clusterInfo = this.updateCluster(con, vc, clusterList);
        vc.setClusters(clusterInfo);

        // 遍历集群列表，获取和更新主机、虚拟机信息
        for (int i=0;i<clusterList.size();i++) {
            // 获取物理主机列表
            HostSystem[] hosts = clusterList.get(i).getHosts();
            // 更新物理主机数据库, 返回物理主机信息，方便更新VM信息
            List<HostInfo> hostInfo = this.updateHost(con, clusterInfo.get(i),hosts);
            clusterInfo.get(i).setHosts(hostInfo);

            // 遍历物理主机列表，获取和更新虚拟机信息
            for (int j=0;j<hostInfo.size();j++) {
                VirtualMachine[] vms = hosts[j].getVms();
                List<VMInfo> vmInfo = this.updateVM(con, hostInfo.get(j), vms);
                hostInfo.get(j).setVms(vmInfo);
            }
        }
        con.commit();
        con.setAutoCommit(true);
        dbPool.close(con);
        vcPool.close(si);

        System.out.println(String.format("[INFO] Update VC:%s end", vc.getHostname()));
    }

    public void deleteOldVersionData(String currentVesion) throws SQLException, InterruptedException {

        System.out.println("[INFO] Delete old version data, current version: " + currentVesion);
        // 获取DB连接池连接
        DBConnectionPool dbPool = DBConnectionPoolFactory.getDBConnectionPool("vmwareops");
        Connection con = dbPool.getConnnection();

        Statement stmt = null;
        stmt = con.createStatement();

        String[] tableName = new String[]{
                "resource_bundle_vsphere_cluster",
                "resource_bundle_vsphere_host",
                "resource_bundle_vsphere_vm",
        };
        for(String table : tableName) {
            String sql_command = String.format(
                    "delete from %s where version!=\'%s\'",
                    table,
                    currentVesion
            );
            boolean isSuccess = stmt.execute(sql_command);
        }
        dbPool.close(con);
    }
     */

}
